package com.rdiot.yx485.ui.bind

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Service
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.location.LocationManager
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import com.clj.fastble.BleManager
import com.gyf.immersionbar.ktx.immersionBar
import com.king.zxing.util.LogUtils
import com.lindroy.iosdialog.IAlertDialog
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseActivity
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.databinding.ActBindBinding
import com.rdiot.yx485.ui.bind.BindActivity.AskTypes.BLE
import com.rdiot.yx485.ui.bind.BindActivity.AskTypes.LOCATION
import com.rdiot.yx485.ui.bind.model.BindViewModel
import com.rdiot.yx485.util.LocationUtils
import com.rdiot.yx485.util.RoomUtils
import com.rdiot.yx485.util.askPermission
import com.rdiot.yx485.util.goToAppSetting
import com.rdiot.yx485.util.goToSystemLocationSetting
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.atomic.AtomicBoolean

/**
 * 添加房间 绑定设备
 * @author mR2hao
 * @date 2022/11/21
 */
class BindActivity : BaseActivity<ActBindBinding>() {
    override fun getLayoutId() = R.layout.act_bind
    private var isPermissionPass = false
    private var isAskingPermission = AtomicBoolean(false)
    private var dialog: IAlertDialog? = null
    private val broadcastReceiver = Receiver()
    private var askList = mutableSetOf(LOCATION, BLE)
    private var isWaitResult = AtomicBoolean(false)

    private lateinit var bindViewModel: BindViewModel

    enum class AskTypes(val type: Int) {
        LOCATION(1),
        BLE(2),
    }

    companion object {
        private const val REQUEST_ENABLE_BT = 10010
    }

    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            statusBarView(binding.v)
            statusBarColor(R.color.transparent)
            navigationBarColor(R.color.main_bg_color)
            statusBarDarkFont(true)
        }
        bindViewModel = ViewModelProvider(this)[BindViewModel::class.java]

//        val isHasMaster = LocalData.familyData.value?.room?.any { it.isMaster }
//        bindViewModel.isBindSub = (RoomUtils.isMaster(LocalData.familyData.value?.code))

//        bindViewModel.testMode()

        binding.nb.setLeftClickListener {
            val navCtrl = findNavController(R.id.fcv)
            if (navCtrl.currentDestination?.id == R.id.selectDeviceTypeFragment) {
                finish()
            } else {
                navCtrl.popBackStack()
            }
        }

        initReceiver()
    }

    /** 初始化广播监听 */
    private fun initReceiver() {
        // 定位
        val locationFilter = IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION)
        // 蓝牙广播
        val bleFilter = IntentFilter().apply {
            addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
            addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
            addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
        }

        registerReceiver(broadcastReceiver, locationFilter)
        registerReceiver(broadcastReceiver, bleFilter)

    }

    /** 设置标题 */
    fun setNBTitle(title: String) {
        binding.nb.setTitle(title)
    }

    private fun checkSwitch() {
        if (isPermissionPass) {
            if (askList.isNotEmpty()) {
                val ite = askList.iterator()
                LogUtils.e("检测列表：$askList")
                while (ite.hasNext()) {
                    val next = ite.next()
                    if (LOCATION == next) {
                        dialog?.dismiss()

                        LogUtils.d("重新检测 定位开关 - ${isLocationEnabled()}")
                        if (isLocationEnabled()) {
                            ite.remove()
                        } else {
                            if (dialog?.isVisible != true) {
                                showNeedOpenLocationDialog()
                            }
                            return
                        }
                    }
                    if (BLE == next) {
                        dialog?.dismiss()
                        if (!isWaitResult.get()) {
                            LogUtils.d("重新检测 蓝牙开关 - ${BleManager.getInstance().isBlueEnable}")
                            if (BleManager.getInstance().isBlueEnable) {
                                ite.remove()
                            } else {
                                if (dialog?.isVisible != true) {
                                    LogUtils.w("1")
                                    showNeedOpenBleDialog()
                                }
                                return
                            }
                        }
                    }
                }
                getLocation()
            } else {
                dialog?.dismiss()
                getLocation()
            }
        }

    }

    private fun getLocation() {
        if (bindViewModel.locationName.isNullOrBlank()) {
            lifecycleScope.launchWhenResumed {
                withContext(Dispatchers.IO) {
                    val cityName = LocationUtils.getLocations(this@BindActivity)
                    LogUtils.d("当前定位：${cityName}")
                    if (cityName.isNotBlank()) {
                        bindViewModel.locationName = cityName
                    } else {
                        getLocation()
                    }
                }
            }
        }
    }

    private fun openBle() {
        LogUtils.i("openBle权限通过[${isPermissionPass}] 检测开关${askList.toList()} ${isAskingPermission.get()}")
        checkSwitch()
        if (!isAskingPermission.getAndSet(true)) {
            LogUtils.d("请求权限")
            if (LocalData.firstBle==1){
                showHint()
            }else {
                askPermission(true, callBack)
            }
        }
    }

    @SuppressLint("MissingPermission")
    private fun askOpenBle() {
        LogUtils.d("请求打开蓝牙")
        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
        isWaitResult.set(true)
    }

    override fun onResume() {
        super.onResume()
        if (!isPermissionPass) {
            openBle()
        } else {
            checkSwitch()
        }
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            if (!isPermissionPass) {
                openBle()
            } else {
                checkSwitch()
            }
        }

    }

    private val callBack = fun(allGranted: Boolean?, _: MutableList<String>?) {
//        LogUtils.i("权限通过: $allGranted - $deniedList")

        when (allGranted) {
            null -> {   //为null表示用户选择了 拒绝并不再询问
                showNeedPermissionDialog()
            }
            true -> {    //表示用户通过权限
                checkSwitch()
            }
            else -> {    //表示用户存在禁止权限操作
                showNeedPermissionDialog()
            }
        }
        allGranted?.let {
            isPermissionPass = it
        }
    }

    private fun showHint() {
        LocalData.firstBle = 0
        dialog?.dismiss()
        dialog = IAlertDialog.build(this)
            .setTitle("位置、蓝牙权限获取说明")
            .setMessage("用于获取当前位置信息、打开蓝牙以发现设备等场景")
            .setNegButtonText(R.string.cancel)
            .setCancelOutside(false)
            .setNegClickListener {
                return@setNegClickListener
            }
            .setAlpha(1.0F)
//            .setPosButtonText(R.string.go_setting)
            .setPosClickListener {
                askPermission(true, callBack)
            }
        dialog?.show()
    }

    private fun showNeedPermissionDialog() {
        if (dialog?.isVisible != true) {
            dialog?.dismiss()
            dialog = IAlertDialog.build(this)
                .setTitle(R.string.hint)
                .setMessage(R.string.need_allow_location)
                .setCancelOutside(false)
                .setNegButtonText(R.string.cancel)
                .setNegClickListener {

                    finish()
                }
                .setDismissible(false)
                .setAlpha(1.0F)
                .setPosButtonText(R.string.allow)
                .setPosClickListener {
                    goToAppSetting(true)
                    isAskingPermission.set(false)
                    dialog?.dismiss()
                }
            dialog?.show()
            LogUtils.e("跳转设置")
        }
    }

    private fun showNeedOpenLocationDialog() {
        if (dialog?.isVisible != true) {
            dialog?.dismiss()
            dialog = IAlertDialog.build(this)
                .setTitle(R.string.hint)
                .setMessage(R.string.need_open_location)
                .setNegButtonText(R.string.cancel)
                .setCancelOutside(false)
                .setNegClickListener {
                    finish()
                }
                .setDismissible(false)
                .setAlpha(1.0F)
                .setPosButtonText(R.string.go_setting)
                .setPosClickListener {
                    askList.add(LOCATION)
                    dialog?.dismiss()
                    goToSystemLocationSetting(true)
                }
            dialog?.show()
        }
    }

    private fun showNeedOpenBleDialog() {
        if (dialog?.isVisible != true) {
            askList.add(BLE)
            dialog?.dismiss()
            dialog = IAlertDialog.build(this)
                .setTitle(R.string.hint)
                .setMessage(R.string.need_enable_ble)
                .setNegButtonText(R.string.cancel)
                .setNegClickListener {
                    finish()
                }
                .setAlpha(1.0F)
                .setPosButtonText(R.string.open)
                .setPosClickListener {
                    askOpenBle()
                    isAskingPermission.set(false)
                }
            dialog?.show()

        }

    }
//
//    private val bleResultLauncher =        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
//        LogUtils.e("设置Wifi返回了")
//    }
//
//    private fun gobleSetting() {
//        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
//        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
//        bleResultLauncher.launch(enableBtIntent)
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        LogUtils.e("onActivityResult(${requestCode}):${resultCode}")
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_OK) {
                LogUtils.i("onActivityResult: 蓝牙打开成功")
                isAskingPermission.set(false)

                dialog?.dismiss()
            } else {
                LogUtils.e("应用需要开启蓝牙功能以发现设备。")
                showNeedOpenBleDialog()
            }
            isWaitResult.set(false)
        }
    }

    /**
     * 判断定位服务是否开启
     *
     * @param
     * @return true 表示开启
     */
    private fun isLocationEnabled(): Boolean {
        val lm = getSystemService(Service.LOCATION_SERVICE) as LocationManager
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
    }

    inner class Receiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                // 定位开关变动
                LocationManager.PROVIDERS_CHANGED_ACTION -> {
                    if (!isLocationEnabled()) {
                        askList.add(LOCATION)
                    } else {
                        askList.remove(LOCATION)
                    }

                    isAskingPermission.set(isLocationEnabled())
                    LogUtils.i("定位开关:${isLocationEnabled()}")
//                    openBle()
                }
                // 蓝牙开关变动
                BluetoothAdapter.ACTION_STATE_CHANGED -> {
                    when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)) {
                        BluetoothAdapter.STATE_TURNING_ON -> LogUtils.i("蓝牙打开中")
                        BluetoothAdapter.STATE_ON -> {
                            askList.remove(BLE)
                            LogUtils.i("蓝牙已打开")
                        }
                        BluetoothAdapter.STATE_TURNING_OFF -> LogUtils.i("蓝牙关闭中")
                        BluetoothAdapter.STATE_OFF -> {
                            isAskingPermission.set(false)
                            askList.add(BLE)
                            LogUtils.i("蓝牙已关闭")
                        }
                    }
                    openBle()

                }
                BluetoothDevice.ACTION_ACL_CONNECTED -> {}
                BluetoothDevice.ACTION_ACL_DISCONNECTED -> {}
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(broadcastReceiver)
    }

}